import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'

import { deepCopy } from 'share/common';
import Searcher from 'components/searcher'
import { Form, Select, Switch, Icon, DatePicker, Button, Spin, message, Popconfirm, Checkbox, Badge, Row, Col } from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;

import moment from 'moment'

import debounce from 'lodash.debounce'
import agencyService from 'containers/setting/agency-setting/agency-setting.service'
import 'styles/setting/agency-setting/agency-relation-form.scss'

class AgencyRelationForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      loadingForms: false, //申请单&报销单，单据信息的loading
      fetching: false,
      proxyVerify: {},  //代理人校验
      proxyOptions: [],    //代理人选项
      proxyOID: '', //代理人oid
      enabled: this.props.defaultValues ? this.props.defaultValues.enabled : true,
      expenseOptions: [],  //报销单选项
      requestOptions: [],  //申请单选项
      loanOptions: [],  //借款单选项
      isCheckAll: true, //是否已增量全选全部
      chosenExpense: [], //选中的报销单数据
      chosenRequest: [], //选中的申请单数据
      chosenLoan: [], //选中的借款单数据
      chosenExpenseOIDs: [], //选中的报销单OID
      chosenRequestOIDs: [], //选中的申请单OID
      chosenLoanOIDs: [], //选中的借款单OID
      startAgencyDate: moment().locale('zh-cn').utcOffset(8),
      endAgencyDate: null,
      selectValue: false
    };
    this.searchValue = debounce(this.searchValue, 250)
  }

  componentDidMount() {
    const { defaultValues } = this.props;
    if (defaultValues) {
      let chosenExpense = [];
      let chosenRequest = [];
      let chosenLoan = [];
      defaultValues.customFormDTOs.map(item => {
        if (item.entityType === 1002) {  //报销单
          chosenExpense.push({formOID: item.formOID, formName: item.formName});
        } else if (item.entityType === 1001) {  //申请单
          chosenRequest.push({formOID: item.formOID, formName: item.formName});
        } else if (item.entityType === 3001) {  //借款单
          chosenLoan.push({formOID: item.formOID, formName: item.formName});
        }
      });
      this.setState({
        chosenExpense,
        chosenRequest,
        chosenLoan,
        isCheckAll: defaultValues.proxyFormScope === 1001,
        proxyOID: defaultValues.proxyOID,
        startAgencyDate: moment(new Date(defaultValues.startDate).format('yyyy-MM-dd')),
        endAgencyDate: defaultValues.endDate ? moment(new Date(defaultValues.endDate).format('yyyy-MM-dd')) : null
      });
      this.getAgencyBill(defaultValues.proxyOID);
    }
  }

  //修改代理人
  handleChange = (value) => {
    this.setState({
      expenseOptions: [],
      requestOptions: [],
      loanOptions: [],
      isCheckAll: true,
      chosenExpense: [],
      chosenRequest: [],
      chosenLoan: []
    });
    if (!value) {
      this.setState({
        proxyVerify: {
          status: 'error',
          help: messages('setting.key12'/*请选择代理人*/)
        },
      })
    } else {
      this.setState({ selectValue: true })
    }
  };

  //查询代理人下拉列表
  handleSearch = (value, id) => {
    let proxyUser = this.props.form.getFieldValue(id);
    if(!value && proxyUser && !this.state.proxyOptions.length) {
      this.setState({
        fetching: false,
        proxyOptions: [JSON.parse(proxyUser)]
      })
    }
    this.searchValue(value)
  };

  searchValue = (value) => {
    let params = {
      page: 0,
      size: 1000,
      keyword: value,
      roleType: 'TENANT'
    };
    if (value && value.length) {
      this.setState({ fetching: true });
      value && value.length && agencyService.getPersonByValueV2(params).then(res => {
        let resultOptions = [];
        let proxyOptions = res.data;
        for (let i = 0; i < proxyOptions.length; i++) {
          let item = proxyOptions[i];
          let proxyIsExist = false;
          this.props.principalInfo.billProxyRuleDTOs.map(proxyItem => {
            item.userOID === proxyItem.proxyOID && (proxyIsExist = true)
          });
          if (item.userOID !== this.props.principalInfo.principalOID && !proxyIsExist) {
            item.text = `${item.fullName} - ${item.employeeID}`
          } else { //除去已存在的代理人
            proxyOptions.splice(i, 1);
            i--
          }
        }
        //只支持工号和姓名搜索，手机和邮箱要去除
        proxyOptions.map(option => {
          if (option.text.indexOf(value.toLowerCase()) > -1 || option.text.indexOf(value.toUpperCase()) > -1) {
            resultOptions.push(option);
          }
        });
        this.setState({ proxyOptions: resultOptions, fetching: false });
      })
    }
  };

  //选择代理人
  handleSelect = (item) => {
    item = JSON.parse(item);
    let proxyVerify = this.state.proxyVerify;
    let leaveDate = moment(item.leavingDate).format('YYYY-MM-DD');
    if (item.status === 1002) {
      proxyVerify = {
        status: 'warning',
        help: messages('setting.key1433',{arg1: leaveDate}/*该员工将于 {arg1} 离职*/) +
              `${this.props.tab === 'apply' ? messages('setting.key2'/*，离职后此代理将自动禁用*/) : ''}`
      }
    } else if (item.status === 1003) {
      proxyVerify = {
        status: 'warning',
        help: messages('setting.key1433',{arg1: leaveDate}/*该员工将于 {arg1} 离职*/) //该员工已于 {time} 离职
      }
    } else {
      proxyVerify = {};
    }
    this.setState({ proxyVerify, proxyOID: item.userOID });
    this.getAgencyBill(item.userOID)
  };

  //获取代理单据
  getAgencyBill = (proxyOID) => {
    this.setState({loadingForms: true});
    agencyService.getAgencyFormList(this.props.tabKey, this.props.principalInfo.principalOID, proxyOID).then(res => {
      this.setState({loadingForms: false});
      let expenseOptions = [];
      let requestOptions = [];
      let loanOptions = [];
      res.data.map(item => {
        item.label = item.formName;
        item.value = item.formOID;
        if (item.entityType === 1002) {  //报销单
          expenseOptions.push(item)
        } else if (item.entityType === 1001) {  //申请单
          requestOptions.push(item)
        } else if (item.entityType === 3001) {  //借款单
          loanOptions.push(item)
        }
      });
      this.setState({ expenseOptions, requestOptions, loanOptions });
    })
  };

  //修改选择的单据
  handleBillsChange = (type, values) => {
    const { requestOptions, expenseOptions, loanOptions } = this.state;
    if (type === 'request') {//申请单
      this.setState({chosenRequest: values});
    } else if (type === 'expense') {//报销单
      this.setState({chosenExpense: values});
    } else if (type === 'loan') {//借款单
      this.setState({chosenLoan: values});
    }
  };

  //开始代理日期 <= 结束代理日期
  disabledStartDate = (startAgencyDate) => {
    let endAgencyDate = moment(moment(this.state.endAgencyDate).format('YYYY-MM-DD 23:59:59'));
    if (!startAgencyDate || !endAgencyDate) {
      return false
    }
    return startAgencyDate.valueOf() > endAgencyDate.valueOf()
  };

  //结束代理日期 >= 开始代理日期 且 结束代理日期 >= 今天
  disabledEndDate = (endAgencyDate) => {
    const startAgencyDate = moment(moment(this.state.startAgencyDate).format('YYYY-MM-DD 00:00:00'));
    if (!endAgencyDate || !startAgencyDate) {
      return false
    }
    if (startAgencyDate.valueOf() < new Date().valueOf() || !this.state.startAgencyDate) {
      return endAgencyDate.valueOf() < new Date(new Date().format('yyyy-MM-dd 00:00:00')).valueOf()
    }
    return endAgencyDate.valueOf() < startAgencyDate.valueOf()
  };

  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        Object.keys(err).map(key => {
          if (key === 'proxyOID' || key === `proxyOID-${this.props.newKey}`) {
            this.setState({
              proxyVerify: {
                status: 'error',
                help: messages('setting.key12'/*请选择代理人*/)
              }
            })
          }
        })
      } else {
        const { newKey, defaultValues } = this.props;
        const { expenseOptions, requestOptions, loanOptions, chosenExpense, chosenRequest, chosenLoan, isCheckAll } = this.state;
        let customFormDTOs = [];
        chosenExpense.map(expense => {
          expenseOptions.map(item => {
            expense.formOID === item.formOID && customFormDTOs.push(item)
          })
        });
        chosenRequest.map(request => {
          requestOptions.map(item => {
            request.formOID === item.formOID && customFormDTOs.push(item)
          })
        });
        chosenLoan.map(loan => {
          loanOptions.map(item => {
            loan.formOID === item.formOID && customFormDTOs.push(item);
          })
        });
        if (!customFormDTOs.length && !isCheckAll) return;
        let proxyInfo;
        try {
          proxyInfo = newKey ? JSON.parse(values[`proxyOID-${newKey}`]) : JSON.parse(values.proxyOID);
        } catch(e) {
          proxyInfo = defaultValues;
        }
        let startDate = newKey ? values[`startDate-${newKey}`] : values.startDate;
        let endDate = newKey ? values[`endDate-${newKey}`] : values.endDate;
        let billProxyRuleDTO = {
          enabled: this.state.enabled,
          endDate: endDate ? endDate.format('YYYY-MM-DD') : null ,
          leavingDate: proxyInfo.leavingDate,
          proxyName: proxyInfo.fullName || proxyInfo.proxyName,
          proxyOID: proxyInfo.userOID || proxyInfo.proxyOID,
          proxyTimeRange: endDate ? 102 : 101, //proxyTimeRange: 101(无限制)、 102(自定义结束时间)
          ruleOID: newKey ? null : defaultValues.ruleOID,
          startDate: startDate.format('YYYY-MM-DD'),
          status: proxyInfo.status,  //status: 1001(正常)、 1002(待离职)、1003(已离职)
          customFormDTOs: isCheckAll ? [] : customFormDTOs,
          proxyFormScope: isCheckAll ? 1001 : 1002,
          emplyeeId: proxyInfo.employeeID || proxyInfo.employeeId || proxyInfo.emplyeeId,
          proxyOperationType: this.props.tabKey
        };
        let principalInfo = this.props.principalInfo;
        let billProxyRuleDTOs = principalInfo.billProxyRuleDTOs;
        newKey && billProxyRuleDTOs.push(billProxyRuleDTO);
        principalInfo.enabled = false;
        billProxyRuleDTOs.map((item, index) => {
          if (item.ruleOID === billProxyRuleDTO.ruleOID) {
            billProxyRuleDTOs[index] = billProxyRuleDTO
          }
        });
        billProxyRuleDTOs.map(item => {
          item.enabled && (principalInfo.enabled = true)
        });
        principalInfo.billProxyRuleDTOs = billProxyRuleDTOs;
        this.setState({ loading: true });
        agencyService.newAgency(principalInfo).then(res => {
          message.success(messages('common.save.success', {name: ''}));
          this.setState({ loading: false });
          newKey ? this.props.submitHandle(res.data, newKey) : this.props.submitHandle(res.data)
        }).catch(e => {
          this.setState({ loading: false });
          message.error(`${messages('common.save.filed')}, ${e.response.data.message}`)
        })
      }
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { defaultValues, newKey } = this.props;
    const { loading, fetching, proxyVerify, proxyOptions, enabled, expenseOptions, requestOptions, loanOptions, selectValue} = this.state;
    const { isCheckAll, chosenExpense, chosenRequest, chosenLoan, proxyOID, loadingForms } = this.state;
    const formItemLayout = {
      labelCol: { span: 2 },
      wrapperCol: { span: 22 },
    };
    const formItemLayoutSmall = {
      labelCol: { span: 2 },
      wrapperCol: { span: 12 },
    };
    return (
      <div className="agency-relation-form">
        <Form onSubmit={e => {this.handleSave(e)}}>
          <FormItem className="agency-form-item"
                    validateStatus={proxyVerify.status || ''}
                    help={proxyVerify.help || ''}
                    label={messages('setting.key13'/*代理人*/)}>
            {getFieldDecorator(newKey ? `proxyOID-${newKey}` : 'proxyOID', {
              rules: [{
                required: true,
                message: messages('common.please.select')
              }],
              initialValue: newKey ? undefined : `${defaultValues.proxyName} - ${defaultValues.emplyeeId}`
            })(
              <Select placeholder={messages('setting.key6'/*请输入姓名/工号*/)}
                      showSearch
                      allowClear
                      filterOption={false}
                      //combobox模式下会导致第一次输入时会导致自动释放输入框的焦点 bug 17503
                      // mode={(proxyOptions.length || selectValue) ? null : 'combobox'}
                      onChange={this.handleChange}
                      onSearch={value => this.handleSearch(value, newKey ? `proxyOID-${newKey}` : 'proxyOID')}
                      onSelect={this.handleSelect}
                      notFoundContent={fetching ? <Spin size="small" /> : messages('setting.key7'/*无匹配结果*/)}
                      getPopupContainer={triggerNode => triggerNode.parentNode}>
                {proxyOptions.map(d => {
                  if (d.text) return <Option key={JSON.stringify(d)}>{d.text}</Option>
                })}
              </Select>
            )}
          </FormItem>
          <FormItem className="date-form-item" label={messages('setting.key14'/*代理日期*/)}>
            <FormItem className="date-form-item">
              {getFieldDecorator(newKey ? `startDate-${newKey}` : 'startDate', {
                rules: [{
                  required: true,
                  message: messages('setting.key15'/*请选择开始时间*/)
                }],
                initialValue: newKey ? moment().locale('zh-cn').utcOffset(8) : moment(new Date(defaultValues.startDate).format('yyyy-MM-dd'))
              })(
                <DatePicker format="YYYY-MM-DD"
                            allowClear={false}
                            disabledDate={this.disabledStartDate}
                            onChange={date => this.setState({startAgencyDate: date})}/>
              )}
            </FormItem>
            <FormItem className="date-form-item">
              {getFieldDecorator(newKey ? `endDate-${newKey}` : 'endDate', {
                initialValue: newKey ? null : (defaultValues.proxyTimeRange === 102 ? moment(new Date(defaultValues.endDate).format('yyyy-MM-dd')) : null)
              })(
                <DatePicker format="YYYY-MM-DD"
                            placeholder={messages('setting.key16'/*无限制*/)}
                            disabledDate={this.disabledEndDate}
                            onChange={date => this.setState({endAgencyDate: date})}/>
              )}
            </FormItem>
          </FormItem>
          <FormItem className="enabled-form-item"
                    colon={false}
                    label={
                      <span>
                        {messages('common.column.status')} ：
                      </span>
                    }>
            {getFieldDecorator(newKey ? `enabled-${newKey}` : 'enabled')(
              <Badge status={enabled ? 'success': 'error'} text={enabled ? messages('common.valid') : messages('common.invalid')} />
            )}
          </FormItem>
          {this.props.tabKey !=3 && <FormItem className="bill-form-item"
                    validateStatus='error'
                    help={isCheckAll || chosenExpense.length || chosenRequest.length || chosenLoan.length || (!expenseOptions.length && !requestOptions.length && !loanOptions.length) ? '' :
                      messages('setting.key17'/*请选择代理单据*/)}
                    label={<span className="ant-form-item-required">{messages('setting.key18'/*代理单据*/)}</span>}>
            {getFieldDecorator(newKey ? `customFormDTOs-${newKey}` : 'customFormDTOs')(
              <div>
                <Row>
                  <Col offset={2} span={12} style={{position: 'absolute', top: '-31px'}}>
                    <Checkbox checked={isCheckAll}
                              onClick={(e)=>this.setState({isCheckAll: e.target.checked})}>
                      {messages('common.all')}
                    </Checkbox>
                  </Col>
                </Row>
                <FormItem {...formItemLayoutSmall}
                          className="bill-form-detail"
                          label={messages('setting.key19'/*报销单*/)}>
                  {expenseOptions.length ? (
                    <div>
                      {getFieldDecorator('chosenOptions1',{
                        initialValue: chosenExpense
                      })(
                        <Searcher type="proxy_form_admin"
                                  listExtraParams={{
                                    customFormType: 1002,
                                    operationCode: this.props.tabKey,
                                    principalOID: this.props.principalInfo.principalOID,
                                    proxyOID: proxyOID
                                  }}
                                  labelKey="formName"
                                  descriptionKey="companyName"
                                  disabled={isCheckAll}
                                  showNumber
                                  isShowSelectAll
                                  isAll={isCheckAll}
                                  showClear={false}
                                  onChange={values => this.handleBillsChange('expense', values)}
                        />
                      )}
                    </div>
                    ) : (<div>
                      {loadingForms ? (<div><Icon type="loading" /></div>) : <div/>}
                    </div>)
                  }
                </FormItem>
                <FormItem {...formItemLayoutSmall}
                          className="bill-form-detail"
                          label={messages('setting.key20'/*申请单*/)}>
                  {requestOptions.length ? (
                    <div>
                      {getFieldDecorator('chosenOptions2',{
                        initialValue: chosenRequest
                      })(
                        <Searcher type="proxy_form_admin"
                                  listExtraParams={{
                                    customFormType: 1001,
                                    operationCode: this.props.tabKey,
                                    principalOID: this.props.principalInfo.principalOID,
                                    proxyOID: proxyOID
                                  }}
                                  labelKey="formName"
                                  descriptionKey="companyName"
                                  disabled={isCheckAll}
                                  showNumber
                                  isShowSelectAll
                                  isAll={isCheckAll}
                                  showClear={false}
                                  onChange={values => this.handleBillsChange('request', values)}
                        />
                      )}
                    </div>
                    ) : (<div>
                      {loadingForms ? (<div><Icon type="loading" /></div>) : <div/>}
                    </div>)
                  }
                </FormItem>
                <FormItem {...formItemLayoutSmall}
                          className="bill-form-detail"
                          label={messages('setting.key1742')/*借款单*/}>
                  {loanOptions.length ? (
                      <div>
                        {getFieldDecorator('chosenOptions3',{
                          initialValue: chosenLoan
                        })(
                          <Searcher type="proxy_form_admin"
                                    listExtraParams={{
                                      customFormType: 3001,
                                      operationCode: this.props.tabKey,
                                      principalOID: this.props.principalInfo.principalOID,
                                      proxyOID: proxyOID
                                    }}
                                    labelKey="formName"
                                    descriptionKey="companyName"
                                    disabled={isCheckAll}
                                    showNumber
                                    isShowSelectAll
                                    isAll={isCheckAll}
                                    showClear={false}
                                    onChange={values => this.handleBillsChange('loan', values)}
                          />
                        )}
                      </div>
                    ) : (<div>
                      {loadingForms ? (<div><Icon type="loading" /></div>) : <div/>}
                    </div>)
                  }
                </FormItem>
              </div>
            )}
          </FormItem>}
          <div>
            <Button type="primary" htmlType="submit" loading={loading} className="save-btn">{messages('common.save')}</Button>
            <Button onClick={this.props.cancelHandle}>{messages('common.cancel')}</Button>
          </div>
        </Form>
      </div>
    )
  }
}

AgencyRelationForm.propTypes = {
  defaultValues: React.PropTypes.object,  //代理关系默认值
  newKey: React.PropTypes.number,         //form表单用于新建formItem时的key
  principalInfo: React.PropTypes.object,  //被代理人信息
  tab: React.PropTypes.string.isRequired, //apply（代理制单）、approve（代理审批）
  cancelHandle: React.PropTypes.func,     //取消新建／编辑
  submitHandle: React.PropTypes.func,     //保存
};

AgencyRelationForm.defaultProps={
  principalInfo: {},
  cancelHandle: () => {},
  submitHandle: () => {},
};


function mapStateToProps() {
  return {}
}

const WrappedAgencyRelationForm = Form.create()(AgencyRelationForm);

export default connect(mapStateToProps)(WrappedAgencyRelationForm);
